#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/18 18:21
    Desc  :
--------------------------------------
"""

from flask import Blueprint, render_template, request
from application import app
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.QuerySetUtils import QuerySetUtils
from common.libs.paginationUtils import ListPaginationUtils
from common.libs.queryListUtils import QueryListUtils
from servers.models.ApiCaseModel import ApiCase
from servers.servers.ApiCaseServices import ApiCaseServices, SimpleApiCaseRun

api_route = Blueprint('api_case', __name__)


def filter_field(form):
    """
    清洗参数
    """
    apiParam = form.get('apiParam')
    if apiParam:
        if len(apiParam) == 1 and apiParam[0] is None:
            return []


# class ApiCaseController:
#
#     def __init__(self):
#         self.apicaseServices = ApiCaseServices()
#
#     @staticmethod
#     @api_route.route('/list', methods = ["POST"])
#     def list():
#         try:
#             form = {} if not request.json else dict(request.json)
#             # 1. 获取当前项目id
#             projectId = request.headers.get('project')
#             form['projectId'] = projectId
#             data = ApiCaseServices().pagination(**form)
#             return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()
#         except Exception as e:
#             app.logger.error(e)
#             return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@api_route.route('/list', methods = ["POST"])
def apiCaseList():
    try:
        form = {} if not request.json else dict(request.json)
        # 1. 获取当前项目id
        projectId = request.headers.get('project')
        form['projectId'] = projectId
        data = ApiCaseServices().pagination(**form)
        return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


@api_route.route('/add', methods = ["POST"])
def apiCaseAdd():
    """
    新增
    :return:
    """
    try:
        form = {} if not request.json else dict(request.json)
        filter_field(form)
        form = QuerySetUtils(ApiCase).filterField(form)
        # 1. 获取当前项目id
        projectId = request.headers.get('project')
        form['projectId'] = projectId
        if form.get('apiName') is None or form.get('apiName') == '':
            return JsonResponse(code = 40002, data = None, message = "apiName不能为空").jsonExit()
        case = ApiCase(**form)
        case.save()
        return JsonResponse(code = 20000, data = case, message = "请求成功").jsonExit()

    except Exception as e:

        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 编辑
@api_route.route('/edit', methods = ["POST"])
def apiCaseEdit():
    try:

        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(ApiCase).filterField(form)
        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code = 40002, data = None, message = "id不能为空").jsonExit()
        case = ApiCase.objects(id = form.get('id'))
        if case.count() == 0:
            return JsonResponse(code = 40005, data = None, message = "用户不存在").jsonExit()
        case.update(**form)
        return JsonResponse(code = 20000, data = case, message = "请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 删除
@api_route.route('/delete', methods = ["POST"])
def apiCaseDelete():
    try:
        form = {} if not request.json else dict(request.json)
        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code = 40002, data = None, message = "id不能为空").jsonExit()
        case = ApiCase.objects(id = form.get('id'))
        if case.count() == 0:
            return JsonResponse(code = 40005, data = None, message = "用户不存在").jsonExit()
        case.delete()
        return JsonResponse(code = 20000, data = None, message = "请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 复制
@api_route.route('/copy', methods = ['POST'])
def apiCaseCopy():
    """
    用例复制
    :return:
    """
    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(ApiCase).filterField(form)

        # 1. 获取当前项目id
        projectId = request.headers.get('project')
        form['projectId'] = projectId
        if form.get('apiName') is None or form.get('apiName') == '':
            return JsonResponse(code = 40002, data = None, message = "apiName不能为空").jsonExit()
        case = ApiCase(**form)
        case.save()
        return JsonResponse(code = 20000, data = case, message = "请求成功").jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 在线调试
@api_route.route('/run', methods = ['POST'])
def apiCaseRun():

    # try:
        form = {} if not request.json else dict(request.json)
        projectId = request.headers.get('project')
        apicase = SimpleApiCaseRun(queryset = form, projectId = projectId)
        apicase.request()
        return JsonResponse(code = 20000, data = apicase.result, message = "请求成功").jsonExit()
    # except Exception as e:
    #     app.logger.error(e)
    #     return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()